package net.html;

import java.io.Writer;

import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.HTML.Tag;

public class Outliner extends HTMLEditorKit.ParserCallback
{
	private Writer out;
	private int level = 0;
	private boolean inHandler = false;
	private static String lineSeparator = System.getProperty("line.separator","\r\n");
	public Outliner(Writer out)
	{
		this.out = out;
	}
	@Override
	public void handleStartTag(Tag t, MutableAttributeSet a, int pos)
	{
		int newLevel = 0;
		if(t == HTML.Tag.H1)
		{
			newLevel = 1;
		}else if(t == HTML.Tag.H2)
		{
			newLevel = 2;
		}else if(t == HTML.Tag.H3)
		{
			newLevel = 3;
		}else
		{
			return;
		}
		this.inHandler = true;
		try
		{
			if(newLevel>this.level)
			{
				for (int i = 0; i < newLevel-this.level; i++)
				{
					out.write("<ul>" + lineSeparator +"<li>");
				}
			}else if(newLevel<this.level)
			{
				for (int i = 0; i < this.level-newLevel; i++)
				{
					out.write(lineSeparator + "</ul>" + lineSeparator);
				}
				out.write(lineSeparator + "<li>");
			}else
			{
				out.write(lineSeparator + "<li>");
			}
			this.level = newLevel;
			out.flush();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	@Override
	public void handleText(char[] data, int pos)
	{
		if(inHandler)
		{
			try
			{
				out.write(data);
				out.flush();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	@Override
	public void flush() throws BadLocationException
	{
		try
		{
			while(this.level-- >0)
			{
				out.write(lineSeparator + "</ul>");
				out.flush();
			}
		}
		catch (Exception e)
		{
		}
	}
}
